package com.hf.eagle.web.struts.admin.manager;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.ebiz.ssi.util.EncryptUtils;
import com.hf.eagle.domain.ModPopedom;
import com.hf.eagle.domain.UserInfo;
import com.hf.eagle.web.base.BaseAction;
import com.hf.eagle.web.base.Keys;
import com.hf.eagle.web.base.Pager;
import com.hf.eagle.web.base.SysConstant;

/**
 * @author Xu,XiaoYuan
 * @version 2011.10.22 00:03
 */
public class UserInfoAction extends BaseAction {

	public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		return this.list(mapping, form, request, response);
	}

	public ActionForward list(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		setNaviStringToScope(request);

		DynaBean dynaBean = (DynaBean) form;
		Pager pager = (Pager) dynaBean.get("pager");
		String user_name_like = (String) dynaBean.get("user_name_like");

		UserInfo userInfo = new UserInfo();
		userInfo.setIs_sys_user(SysConstant.IS_BACK_USER);
		userInfo.setIs_del(0);
		super.copyProperties(userInfo, form);
		userInfo.getMap().put("user_name_like", user_name_like);

		Long recordCount = super.getFacade().getUserInfoService().getUserInfoCount(userInfo);
		pager.init(recordCount, pager.getPageSize(), pager.getRequestPage());
		userInfo.getRow().setFirst(pager.getFirstRow());
		userInfo.getRow().setCount(pager.getLastRow());

		List<UserInfo> list = super.getFacade().getUserInfoService().getUserInfoPaginatedList(userInfo);
		request.setAttribute("entityList", list);

		return mapping.findForward("list");
	}

	public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		setNaviStringToScope(request);

		return mapping.findForward("input");
	}

	public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		setNaviStringToScope(request);

		DynaBean dynaBean = (DynaBean) form;
		String user_id = (String) dynaBean.get("user_id");
		String mod_id = (String) dynaBean.get("mod_id");

		UserInfo userInfo = new UserInfo();
		userInfo.setUser_id(Long.valueOf(user_id));
		userInfo.setIs_del(0);
		userInfo = super.getFacade().getUserInfoService().getUserInfo(userInfo);
		if (null != userInfo) {
			userInfo.setQueryString(super.serialize(request, "user_id", "method", "mod_id"));
		}
		super.copyProperties(form, userInfo);

		dynaBean.set("mod_id", mod_id);

		return mapping.findForward("input");
	}

	public ActionForward view(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		setNaviStringToScope(request);

		DynaBean dynaBean = (DynaBean) form;
		String user_id = (String) dynaBean.get("user_id");

		UserInfo userInfo = new UserInfo();
		userInfo.setUser_id(Long.valueOf(user_id));
		userInfo = super.getFacade().getUserInfoService().getUserInfo(userInfo);
		super.copyProperties(form, userInfo);

		return mapping.findForward("view");
	}

	public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		DynaBean dynaBean = (DynaBean) form;
		String mod_id = (String) dynaBean.get("mod_id");

		UserInfo entity = new UserInfo();
		super.copyProperties(entity, form);

		String password = entity.getPassword();

		UserInfo userInfo = null;
		if (null == entity.getUser_id()) {
			userInfo = getFacade().getUserInfoService().getUserInfo(new UserInfo(entity.getUser_name()));
			if (null != userInfo) {
				saveError(request, "entity.exists", new String[] { userInfo.getUser_name() });
			} else {
				entity.setPassword(EncryptUtils.MD5Encode(password));
				entity.setLogin_count(0);
				entity.setIs_del(0);
				entity.setIs_admin(0);
				super.getFacade().getUserInfoService().createUserInfo(entity);
				saveMessage(request, "entity.inserted");
			}
		} else {
			userInfo = getFacade().getUserInfoService().getUserInfo(new UserInfo(entity.getUser_id()));
			if (null != userInfo) {
				if (!password.equalsIgnoreCase(userInfo.getPassword())) {
					entity.setPassword(EncryptUtils.MD5Encode(password));
				}
				super.getFacade().getUserInfoService().modifyUserInfo(entity);
				saveMessage(request, "entity.updated");
			} else {
				saveError(request, "entity.missing");
			}
		}

		// the line below is added for pagination
		StringBuffer pathBuffer = new StringBuffer();
		pathBuffer.append(mapping.findForward("success").getPath());
		pathBuffer.append("&mod_id=" + mod_id);
		pathBuffer.append("&");
		pathBuffer.append(super.encodeSerializedQueryString(entity.getQueryString()));
		ActionForward forward = new ActionForward(pathBuffer.toString(), true);
		// end
		return forward;
	}

	public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		DynaBean dynaBean = (DynaBean) form;
		String user_id = (String) dynaBean.get("user_id");
		String mod_id = (String) dynaBean.get("mod_id");
		String[] pks = (String[]) dynaBean.get("pks");

		UserInfo userInfo = new UserInfo();
		userInfo.setMod_id(Long.valueOf(mod_id));
		userInfo.setIs_del(1);
		if (!StringUtils.isBlank(user_id) && GenericValidator.isLong(user_id)) {
			userInfo.setUser_id(Long.valueOf(user_id));
			super.getFacade().getUserInfoService().removeUserInfo(userInfo);
			saveMessage(request, "entity.deleted");
		} else if (!ArrayUtils.isEmpty(pks)) {
			userInfo.getMap().put("pks", pks);
			super.getFacade().getUserInfoService().removeUserInfo(userInfo);
			saveMessage(request, "entity.deleted");
		}

		// the line below is added for pagination
		StringBuffer pathBuffer = new StringBuffer();
		pathBuffer.append(mapping.findForward("success").getPath());
		pathBuffer.append("&mod_id=" + mod_id + "&");
		pathBuffer.append(encodeSerializedQueryString(serialize(request, "user_id", "method", "mod_id")));
		ActionForward forward = new ActionForward(pathBuffer.toString(), true);
		// end
		return forward;
	}

	public ActionForward saveModpopedom(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		setNaviStringToScope(request);

		DynaBean dynaBean = (DynaBean) form;
		String user_id = (String) dynaBean.get("user_id");
		String mod_id = (String) dynaBean.get("mod_id");
		String[] mod_id_ = request.getParameterValues("mod_id_");

		List<ModPopedom> ModPopedomList = new ArrayList<ModPopedom>();
		if (null != mod_id_ && mod_id_.length > 0) {
			for (int i = 0; i < mod_id_.length; i++) {
				ModPopedom modPopedom = new ModPopedom();
				modPopedom.setUser_id(Long.valueOf(user_id));
				modPopedom.setMod_id(Long.valueOf(mod_id_[i]));
				ModPopedomList.add(modPopedom);
			}
		}

		ModPopedom modPopedom = new ModPopedom();
		modPopedom.setUser_id(Long.valueOf(user_id));
		modPopedom.setModPopedomList(ModPopedomList);

		super.getFacade().getModPopedomService().modifyModPopedom(modPopedom);

		HttpSession session = request.getSession(false);
		UserInfo ui = (UserInfo) session.getAttribute(Keys.ADMIN_USER);

		String msg = super.getMessage(request, "operate.ok");

		if (String.valueOf(ui.getUser_id()).equals(user_id)) {
			super.renderJavaScript(response, "alert('" + msg + "');location.href='UserInfo.do?mod_id=" + mod_id
					+ "';window.parent.frames['leftFrame'].location.reload(true);");
		} else {
			super.renderJavaScript(response, "alert('" + msg + "');location.href='UserInfo.do?mod_id=" + mod_id + "';");
		}

		return null;
	}

	public ActionForward ValidateUserName(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		DynaBean dynaBean = (DynaBean) form;
		String user_name = (String) dynaBean.get("user_name");
		String isExist = "1";

		if (StringUtils.isNotBlank(user_name)) {
			UserInfo userInfo = new UserInfo();
			userInfo.setUser_name(user_name);
			userInfo.setIs_del(0);
			userInfo = super.getFacade().getUserInfoService().getUserInfo(userInfo);
			if (null == userInfo) {
				isExist = "0";
			} else {
				isExist = "1";
			}
		} else {
			isExist = "2";
		}

		super.renderJson(response, isExist);
		return null;
	}

}
